﻿using Aliyun.OSS.Common;
using Md.Api.DDD;
using Md.Api.Model;

namespace Md.Util.Service;
/// <summary>
/// API统一抽象类
/// </summary>
/// <typeparam name="P">统一请求实体</typeparam>
public abstract class ApiBase<P>: ApiBaseBase<P> where P : RequestBaseModel, new()
{
    //初始化异步锁
    private static SemaphoreSlim _mutex = new SemaphoreSlim(10);
    /// <summary>
    /// 返回实体
    /// </summary>
    public ResponseMessageModel Result { get; set; } = new ResponseMessageModel();
    /// <summary>
    /// 参数
    /// </summary>
    public P Parameter { get; set; } = new P();
    /// <summary>
    /// 文件统一保存路径
    /// </summary>
    public string FileBasePath = JsonConfig.JsonRead("MdSettings:MdFilePath");
    /// 业务实现方法
    /// </summary>
    protected abstract void ExecuteMethod();
    /// <summary>
    /// 验证
    /// </summary>
    protected virtual bool Validate()
    {
        return true;
    }
    /// <summary>
    /// 执行
    /// </summary>
    /// <returns></returns>
    public override ResponseMessageModel Execute(P model)
    {
        var timeSpan = new TimeSpan(0, 5, 0);

        _mutex.Wait(timeSpan);

        try
        {
            //接收参数
            Parameter = model;

            //执行验证
            if (!Validate())
            {
                return Result;
            }

            //执行业务方法
            ExecuteMethod();
        }
        catch(OssException ossEx)
        {
            #region 异常处理
            Result.Rows = null;
            Result.Data = null;
            Result.Code = "500";
            Result.Msg = ossEx.Message;
            Result.IsSuccess = false;

            //StringBuilder DebugeInfo = new StringBuilder();
            //DebugeInfo.Append("Parameter:" + JsonConvert.SerializeObject(this.Parameter) + "\r\n");
            //DebugeInfo.Append("Exception:" + ex.Message + "|" + ex.StackTrace + "\r\n");
            // LoggerFactory.Instance.Logger_Debug(DebugeInfo.ToString(), "ExecuteMethodError");
            #endregion
        }
        catch (Exception ex)
        {
            #region 异常处理
            Result.Rows = null;
            Result.Data = null;
            Result.Code = "500";
            Result.Msg = ex.Message;
            Result.IsSuccess = false;

            //StringBuilder DebugeInfo = new StringBuilder();
            //DebugeInfo.Append("Parameter:" + JsonConvert.SerializeObject(this.Parameter) + "\r\n");
            //DebugeInfo.Append("Exception:" + ex.Message + "|" + ex.StackTrace + "\r\n");
            // LoggerFactory.Instance.Logger_Debug(DebugeInfo.ToString(), "ExecuteMethodError");
            #endregion
        }

        //异步锁释放
        _mutex.Release();

        return Result;
    }
}

